package com.ikun.yummy.activitys.main.fragment.home;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.ikun.yummy.App;
import com.ikun.yummy.R;
import com.ikun.yummy.activitys.details.DetailActivity;
import com.ikun.yummy.activitys.login.LoginActivity;
import com.ikun.yummy.activitys.main.MainActivity;
import com.ikun.yummy.activitys.post.PostActivity;
import com.ikun.yummy.adapter.CookListAdapter;
import com.ikun.yummy.adapter.ViewPagerAdapter;
import com.ikun.yummy.bean.CookInfo;
import com.ikun.yummy.bean.LikeInfo;
import com.ikun.yummy.bean.UserInfo;
import com.ikun.yummy.manager.CookOpManager;
import com.ikun.yummy.manager.LikeOpManager;
import com.ikun.yummy.manager.UserOpManager;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {
    private ViewPager imageViewPager;
    private int timerCount=0;
    private final Handler handler = new Handler();
    Runnable timerTask = new Runnable() {
        @Override
        public void run() {
            timerCount++;
            if (timerCount==3){
                timerCount=0;
            }
            imageViewPager.setCurrentItem(timerCount);
            handler.postDelayed(this, 5000);
        }
    };
    private final List<CookInfo> cookList =new ArrayList<>();
    private CookListAdapter adp;
    private LikeOpManager likeOpManager;
    private UserOpManager userOpManager;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View root = inflater.inflate(R.layout.fragment_home, container, false);
        initView(root);
        exe();
        return root;
    }
    private void exe() {//每5秒轮换图片
        handler.postDelayed(timerTask, 5000);
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        handler.removeCallbacks(timerTask);
    }
    private void initView(View root) {
        //初始化轮播图数据
        //将资源图添加到imageViewList中
        List<ImageView> imageViewList = new ArrayList<>();
        imageViewList.add(CreateImageView(R.mipmap.main_show1));
        imageViewList.add(CreateImageView(R.mipmap.main_show2));
        imageViewList.add(CreateImageView(R.mipmap.main_show3));
        imageViewPager = root.findViewById(R.id.home_vp);
        ViewPagerAdapter imageViewPagerAdapter = new ViewPagerAdapter(getActivity(), imageViewList);
        imageViewPager.setAdapter(imageViewPagerAdapter); //setAdapter将包含实体类的列表数据显示在轮播图上面

        likeOpManager=new LikeOpManager(requireContext());
        userOpManager=new UserOpManager(requireContext());
        //发布按钮
        root.findViewById(R.id.home_addPost).setOnClickListener(v -> {
            String user= App.sp.getString("username","null");
            if (!user.equals("null")){//是否这个用户存在
                UserOpManager userOpManager=new UserOpManager(requireContext());
                UserInfo userInfo = userOpManager.queryUser(user);
                if (userInfo.loginstate.equals("1")){  //"1"用户是处于登录状态，是否为登录状态
                    requireContext().startActivity(new Intent(requireContext(), PostActivity.class));
                }else {
                    startActivity(new Intent(requireContext(), LoginActivity.class));
                }
            }else {
                startActivity(new Intent(requireContext(), LoginActivity.class));
            }
        });
        ListView listview = root.findViewById(R.id.home_lv);
        adp=new CookListAdapter(requireContext(), R.layout.item_cook, cookList,1, (v, cookBean, position) -> {
            String user=App.sp.getString("username","null");//"null"作为第一个值取不到的默认值，方便下面使用这个变量
            if (!user.equals("null")){
                UserInfo userInfo = userOpManager.queryUser(user);
                if (userInfo.loginstate.equals("1")){//有用户登录
                    if(!cookBean.cookid.equals("") && !cookBean.username.equals("")){ //可能点赞
                        List<LikeInfo> list = likeOpManager.query(cookBean.cookid, userInfo.username);
                        String likeid="";
                        if (list!=null){
                            for (LikeInfo l :list) {
                                if (l.cookid.equals(cookBean.cookid)&&userInfo.username.equals(l.username)){
                                    likeid=l.likeid;
                                    break;
                                }
                            }
                            if (!likeid.equals("")){
                                cookList.get(position).like=false;
                                likeOpManager.delete(likeid);//取消点赞
                            }else{                                      //点赞
                                List<LikeInfo> likeInfo = likeOpManager.insert(new LikeInfo(cookBean.cookid, user, cookBean.username, cookBean.cookname));
                                if (likeInfo!=null && likeInfo.get(0)!=null){
                                    cookList.get(position).likeid=likeInfo.get(0).likeid;
                                    cookList.get(position).like=true;
                                }
                            }
                        }else{
                            List<LikeInfo> likeInfo = likeOpManager.insert(new LikeInfo(cookBean.cookid, user, cookBean.username, cookBean.cookname));
                            if (likeInfo!=null && likeInfo.get(0)!=null){
                                cookList.get(position).likeid=likeInfo.get(0).likeid;
                                cookList.get(position).like=true;
                            }
                        }
                    }else{//说明没点赞，insert
                        List<LikeInfo> likeInfo = likeOpManager.insert(new LikeInfo(cookBean.cookid, user, cookBean.username, cookBean.cookname));
                        if (likeInfo!=null && likeInfo.get(0)!=null){
                            cookList.get(position).likeid=likeInfo.get(0).likeid;
                            cookList.get(position).like=true;
                        }
                    }
                    adp.notifyDataSetChanged();
                }else{
                    Toast.makeText(requireContext(),"登陆后才能点赞",Toast.LENGTH_SHORT).show();
                }
            }else{
                Toast.makeText(requireContext(),"登陆后才能点赞",Toast.LENGTH_SHORT).show();
            }
        });
        listview.setAdapter(adp);
        listview.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent=new Intent(requireContext(), DetailActivity.class);
            intent.putExtra("cookid", cookList.get(position).cookid);
            startActivityForResult(intent,11);
        });
    }
    private void refresh() {
        cookList.clear();
        CookOpManager cookOpManager=new CookOpManager(requireContext());
        List<CookInfo> list =cookOpManager.queryAll();
        String user=App.sp.getString("username","null");
        UserOpManager userOpManager=new UserOpManager(requireContext());
        UserInfo userInfo =userOpManager.queryUser(user);
        if (list!=null){
            for (int i = 0; i < list.size(); i++) {//遍历cook列表
                CookInfo bean = list.get(i);
                if (!user.equals("null")&&userInfo.loginstate.equals("1")){
                    List<LikeInfo> likeInfos=likeOpManager.query(bean.cookid,user);
                    boolean hasLike=false;
                    String likeid="";
                    if (likeInfos!=null){
                        for (LikeInfo l :likeInfos) {//遍历是否点赞
                            if (l.cookid.equals(bean.cookid)&&l.username.equals(userInfo.username)){//用like表的两个值和bean匹配
                                hasLike=true;
                                likeid=l.likeid;
                                break;
                            }
                        }
                    }
                    if (hasLike){
                        bean.likeid=likeid;
                        bean.like=true;
                    }else{
                       bean.like=false;
                    }
                }
                cookList.add(bean);
            }
            adp.notifyDataSetChanged();
        }
    }
    private ImageView CreateImageView(int resourceId) {
        ImageView imageView = new ImageView(getActivity());
        imageView.setBackgroundResource(resourceId);
        return imageView;
    }
    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==11 && resultCode==22){
            if (data!=null && data.getBooleanExtra("isMyCook",false)){
                //菜谱信息中点击到了我自己的页面，跳转到me
                MainActivity a = (MainActivity) getActivity();
                a.startFrgament(R.id.navigation_me);
            }
        }
    }
}